package com.kk.miaosha.service.impl;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.generator.SnowflakeGenerator;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kk.miaosha.entity.Item;
import com.kk.miaosha.entity.ItemKill;
import com.kk.miaosha.entity.ItemKillSuccess;
import com.kk.miaosha.entity.RandomCode;
import com.kk.miaosha.mapper.ItemKillMapper;
import com.kk.miaosha.mapper.ItemKillSuccessMapper;
import com.kk.miaosha.mapper.ItemMapper;
import com.kk.miaosha.service.ItemKillSuccessService;
import com.kk.miaosha.service.RandomCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 秒杀成功订单表 服务实现类
 * </p>
 *
 * @author kk
 * @since 2020-09-18
 */
@Service
@Slf4j
@Transactional
public class ItemKillSuccessServiceImpl extends ServiceImpl<ItemKillSuccessMapper, ItemKillSuccess> implements ItemKillSuccessService {
    @Resource
    private ItemKillMapper itemKillMapper;
    @Resource
    private ItemMapper itemMapper;
    @Resource
    private ItemKillSuccessMapper iksMapper;
    @Resource
    private RandomCodeService randomCodeService;

    @Override
    @Transactional
    public void updateStock(Integer killId, Integer itemId, Integer userId) {
        ItemKillSuccess itemKillSuccess=new ItemKillSuccess();
        itemKillSuccess.setKillId(killId)
                .setItemId(itemId)
                .setUserId(userId)
                .setId(generateSnowId());
        iksMapper.insert(itemKillSuccess);
        //秒杀活动更新数据
        ItemKill itemKill = itemKillMapper.selectById(killId);
        itemKill.setTotal(itemKill.getTotal()-1);
        itemKillMapper.updateById(itemKill);

        //商品更新数据
        Item item = itemMapper.selectById(itemId);
        item.setStock(item.getStock()-1);
        itemMapper.updateById(item);
    }

    //生成不重复的雪花id
    private String generateSnowId(){
        SnowflakeGenerator snow=new SnowflakeGenerator();
        Long snowId = snow.next();
        boolean flag = randomCodeService.findSnowId(snowId);
        while (flag){
            snowId = snow.next();
            flag = randomCodeService.findSnowId(snowId);
        }
        //存入RandomCode
        randomCodeService.save(new RandomCode().setCode(Convert.toStr(snowId)));
        return Convert.toStr(snowId);
    }
}
